// src/main.rs
use winit::{
    event::{Event, WindowEvent},
    event_loop::EventLoop,
    window::WindowBuilder,
};
use bgfx_rs::bgfx;

struct GraphicsContext {
    window: std::sync::Arc<winit::window::Window>,
}

impl GraphicsContext {
    fn new(window: &winit::window::Window) -> Result<Self, Box<dyn std::error::Error>> {
        let mut pd = bgfx::PlatformData::default();
        pd.ndt = None;
        pd.nwh = Some(window.as_raw_handle());

        let init = bgfx::Init {
            platform_data: pd,
            renderer_type: bgfx::RendererType::Default,
            resolution: bgfx::Resolution {
                width: window.inner_size().width,
                height: window.inner_size().height,
                reset: bgfx::ResetFlags::empty().bits(),
                ..Default::default()
            },
            ..Default::default()
        };

        bgfx::render_frame(-1);
        bgfx::init(&init)?;

        Ok(Self {
            window: std::sync::Arc::new(window.clone()),
        })
    }

    fn resize(&mut self, width: u32, height: u32) {
        bgfx::reset(width, height, bgfx::ResetFlags::empty());
        bgfx::set_view_rect(0, 0, 0, width, height);
    }

    fn begin_frame(&mut self) {
        let size = self.window.inner_size();
        bgfx::set_view_clear(0, bgfx::ClearFlags::COLOR, 0x303030ff, 1.0, 0);
        bgfx::set_view_rect(0, 0, 0, size.width, size.height);
        bgfx::touch(0);
    }

    fn end_frame(&mut self) {
        bgfx::frame();
    }

    fn draw_rect(&self, x: u16, y: u16, width: u16, height: u16, color: u32) {
        bgfx::dbg_text_clear(0, false);
        for i in y..y + height {
            bgfx::dbg_text_printf(x as i16, i as i16, (color >> 24) as u8, &" ".repeat(width as usize));
        }
    }
}

struct UserInterface;

impl UserInterface {
    fn render(&self, graphics: &mut GraphicsContext) {
        // Draw IDE layout
        graphics.draw_rect(0, 0, 250, 720, 0x252526ff);    // File explorer
        graphics.draw_rect(250, 0, 1030, 670, 0x1e1e1eff); // Editor
        graphics.draw_rect(250, 670, 1030, 50, 0x252526ff); // Terminal

        // UI text
        bgfx::dbg_text_printf(1, 1, 0x0f, "Carver IDE");
        bgfx::dbg_text_printf(1, 3, 0x8f, "File Explorer");
        bgfx::dbg_text_printf(260, 1, 0x8f, "Editor");
        bgfx::dbg_text_printf(260, 672, 0x8f, "Terminal");
    }
}

fn main() -> Result<(), Box<dyn std::error::Error>> {
    let event_loop = EventLoop::new()?;
    let window = WindowBuilder::new()
        .with_title("Carver IDE")
        .with_inner_size(winit::dpi::LogicalSize::new(1280, 720))
        .build(&event_loop)?;

    let mut graphics = GraphicsContext::new(&window)?;
    let ui = UserInterface;

    event_loop.run(move |event, elwt| {
        match event {
            Event::WindowEvent { event, .. } => match event {
                WindowEvent::CloseRequested => elwt.exit(),
                WindowEvent::Resized(size) => graphics.resize(size.width, size.height),
                _ => (),
            },
            Event::AboutToWait => {
                graphics.begin_frame();
                ui.render(&mut graphics);
                graphics.end_frame();
            }
            _ => (),
        }
    })?;

    Ok(())
}